<?php
declare (strict_types = 1);

namespace app\api\model\v1;

use think\Model;

/**
 * @mixin \think\Model
 * 用户
 */
class Admins extends AppModel
{
    //
    protected $hidden = [
        'password'
    ];

    const IS_LOGIN_ONE = 1;
    const IS_LOGIN_TWO = 2;

    //是否允许登录后台
    public static $is_login = array(
        self::IS_LOGIN_ONE => '允许',
        self::IS_LOGIN_TWO => '禁止'
    );

    public function unit(){
        return $this->belongsTo(GatherCompany::class,'unit_id');
    }

    //
    public function roles()
    {
        return $this->belongsToMany(AuthGroup::class,'auth_group_access','group_id','uid');
    }

    //整改
    public function rectification(){
        return $this->hasMany(Rectification::class,'unit_id')->field('id,unit_id');
    }
    //有效整改
    public function yxZG(){
        return $this->hasMany(Rectification::class,'unit_id')->field('id,unit_id');
    }
    //无效整改
    public function wxZG(){
        return $this->hasMany(Rectification::class,'unit_id')->field('id,unit_id');
    }
    //未整改
    public function wZg(){
        return $this->hasMany(Rectification::class,'unit_id')->field('id,unit_id');
    }

    /**
     * @param $arrData
     * @param $create_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 导入
     */
    public static function saveAdminExcel($arrData, $create_id)
    {
        if (!empty($arrData)) {
            foreach ($arrData as $key => $v) {
                $is_ex = self::where(['mobile'=>$v[0]])->find();
                if (is_null($is_ex)) { //为空的时候新增
                    $unit = GatherCompany::where(['gather_company_title'=>trim($v[2])])->find();
                    if (!is_null($unit)){
                        $unit_id = $unit->id;
                    }else{
                        $unit_id = 0;
                    }
                    $data = [
                        'mobile' => $v[0] ?? '',
                        'username' => trim($v[1]) ?? '',
                        'nickname'=>trim($v[1]) ?? '',
                        'email' => $v[0] . '@139.com' ?? '',
                        'password' => password_hash('111111', PASSWORD_DEFAULT),
                        'unit_id' =>$unit_id,
                        'is_login'=>self::IS_LOGIN_TWO,
                        'create_id' => $create_id
                    ];
                    $uid = Admins::create($data)->id;
                    //添加角色表
                    AuthGroupAccess::create([
                        'uid'=>$uid,
                        'group_id'=>3 //采集员
                    ]);
                }
            }
            $result = true;
        } else {
            $result = false;
        }
        return $result;
    }
}
